import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '@/api/request'

export interface UserInfo {
  id: number
  username: string
  nickname: string
  avatar: string
  role: string
}

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>('')
    const userInfo = ref<UserInfo | null>(null)

    // 计算属性：是否已登录
    const isLoggedIn = computed(() => !!token.value)

    // 登录
    const login = async (username: string, password: string) => {
      try {
        // TODO: 实现实际的登录API调用
        // 模拟登录成功
        token.value = 'mock_token'
        userInfo.value = {
          id: 1,
          username: username,
          nickname: '管理员',
          avatar: 'https://api.dicebear.com/7.x/adventurer/svg?seed=admin',
          role: '系统管理员',
        }
        return true
      } catch (error) {
        console.error('登录失败:', error)
        return false
      }
    }

    // 获取用户信息
    const getUserInfo = async () => {
      const data = await request.get<UserInfo>('/auth/info')
      userInfo.value = data
    }

    // 登出
    const logout = () => {
      token.value = ''
      userInfo.value = null
    }

    return {
      token,
      userInfo,
      isLoggedIn,
      login,
      getUserInfo,
      logout,
    }
  },
  {
    persist: true,
  },
)
